package com.sky.web;

import cn.hutool.core.bean.BeanUtil;
import com.sky.api.member.MemberFeignService;
import com.sky.dto.member.UmsMemberVO;
import com.sky.utils.R;
import com.sky.vo.UserRegisterVo;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.Map;

@Controller
public class RegisterController {

    @Resource
    private MemberFeignService memberFeignService;

    @PostMapping("/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        Map<String, String> errors = new HashMap<>(16);
        if (result.hasErrors()){
            result.getFieldErrors().forEach(fieldError -> {
                errors.put(fieldError.getField(),fieldError.getDefaultMessage());
            });
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:/reg.html";
        }

        // 进行用户信息注册
        UmsMemberVO memberVO = new UmsMemberVO();
        BeanUtil.copyProperties(vo,memberVO);
        R<Boolean> addUmsMember = memberFeignService.addUmsMember(memberVO);
        if (addUmsMember.getCode() == 0){
            return "redirect:/login.html";
        } else {
            errors.put("msg",addUmsMember.getMsg());
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:/reg.html";
        }
    }
}
